package web;

import com.google.gson.Gson;
import dao.impl.*;
import pojo.*;
import service.UsecaseService;
import service.impl.UsecaseServiceImpl;
import utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

public class UsecaseServlet extends BaseServlet{

    private UsecaseService service = new UsecaseServiceImpl();

    protected void saveUsecase(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Gson gson = new Gson();
        int count = 0;
        Plan plan = new Plan(req.getParameter("time"),req.getParameter("cid"),req.getParameter("uid"),req.getParameter("module"));
        System.out.println(plan.toString());
        System.out.println(req.getParameter("case"));
        String module = plan.getModule();
        if (module.equals("collect")){
            count = service.saveUsecase(Collect.class,plan,gson.fromJson(req.getParameter("case"),Collect.class));
        }else if(module.equals("comment")) {
            count = service.saveUsecase(Comment.class,plan,gson.fromJson(req.getParameter("case"),Comment.class));
        }else if(module.equals("like")){
            count = service.saveUsecase(Like.class,plan,gson.fromJson(req.getParameter("case"),Like.class));
        }else if(module.equals("login")){
            count = service.saveUsecase(Login.class,plan,gson.fromJson(req.getParameter("case"),Login.class));
        }else if(module.equals("loginicon")){
            count = service.saveUsecase(LoginIcon.class,plan,gson.fromJson(req.getParameter("case"),LoginIcon.class));
        }else if(module.equals("page")){
            count = service.saveUsecase(Page.class,plan,gson.fromJson(req.getParameter("case"),Page.class));
        }else if(module.equals("sort")){
            count = service.saveUsecase(Sort.class,plan,gson.fromJson(req.getParameter("case"),Sort.class));
        }else {
            System.out.println("saveUsecase-> 未找到module");
        }
        resp.getWriter().write("成功更改"+count+"条");
    }

    protected void getAllUsecase(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException{
        String uid = req.getParameter("uid");
        System.out.println("getAllUsecase -> uid: "+uid);

        Gson gson = new Gson();

        resp.getWriter().write(gson.toJson(service.getAllUsecase(uid)));
    }
}
